package me.zhengjie.log.utils;


import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

public class RequestParamUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 判断当前是否为外部HTTP请求调用（有Request上下文）
     */
    public static boolean isExternalRequest() {
        return RequestContextHolder.getRequestAttributes() != null;
    }

    /**
     * 将查询参数和请求体参数统一转换为Map，键名为"jsonBody"
     *
     * @return 包含所有参数的Map（{jsonBody: {查询参数 + 请求体参数}}）
     */
    public static Map<String, Object> getAllParamsAsJsonBody() {

        Map<String, Object> result = new HashMap<>();
        // 如果是内部调用，直接返回空Map
        if (!isExternalRequest()) {
            return result;
        }

        // 存储所有参数的统一对象
        Map<String, Object> allParams = new LinkedHashMap<>();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes != null ? attributes.getRequest() : null;

        if (request == null) {
            return result;
        }

        // 1. 处理查询参数（转换为Map<Object, Object>，与JSON体格式一致）
        Map<String, Object> queryParams = new LinkedHashMap<>();
        Enumeration<String> queryNames = request.getParameterNames();
        while (queryNames.hasMoreElements()) {
            String name = queryNames.nextElement();
            // 转换为Object类型（与JSON解析结果保持一致）
            queryParams.put(name, request.getParameter(name));
        }
        // 将查询参数放入统一对象
        allParams.putAll(queryParams);

        // 2. 处理请求体参数（JSON格式），并合并到统一对象
        String method = request.getMethod().toUpperCase();
        if (Arrays.asList("POST", "PUT", "PATCH", "DELETE").contains(method)) {
            String contentType = request.getContentType();
            if (contentType != null && contentType.contains("application/json")) {
                Object bodyParams = parseJsonBody(request);
                // 如果是有效的Map，合并到统一对象
                if (bodyParams instanceof Map) {
                    allParams.putAll((Map<? extends String, ?>) bodyParams);
                } else if (bodyParams instanceof String && !((String) bodyParams).startsWith("JSON解析失败")) {
                    // 处理解析异常外的其他情况（如空JSON）
                    allParams.put("bodyInfo", bodyParams);
                }
            }
        }

        // 用"jsonBody"作为键存储所有参数
        result.put("queryParams", allParams);
        return result;
    }

    /**
     * 解析JSON请求体
     */
    private static Object parseJsonBody(HttpServletRequest request) {
        try {
            request.getInputStream().mark(1);
            int firstByte = request.getInputStream().read();
            if (firstByte == -1) {
                return Collections.emptyMap(); // 空JSON返回空Map
            }

            request.getInputStream().reset();
            return objectMapper.readValue(request.getInputStream(), Map.class);
        } catch (IOException e) {
            return "JSON解析失败：" + e.getMessage();
        }
    }

    /**
     * 将统一参数转换为字符串
     */
    public static String getAllParamsAsString(Object[] args, ThreadLocal<Integer> CALL_LEVEL) {
        Object queryParams = null;
        if (CALL_LEVEL.get() != null && CALL_LEVEL.get() == 1) {
            Map<String, Object> allParamsAsJsonBody = getAllParamsAsJsonBody();
            queryParams = allParamsAsJsonBody.get("queryParams");
        }
        if (queryParams == null || ((LinkedHashMap<?, ?>) queryParams).isEmpty()) {
            return args != null && args.length > 0 ? JSON.toJSONString(args[0]) : "";
        }
        return JSON.toJSONString(queryParams);
    }
}
